package idiolect.core;

import idiolect.webstorage.WebStorageDialog;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Starter extends JFrame implements ActionListener {
    private final JButton openFile;
    private final JButton browseWebStorage;
    private final JButton createNew;
    private final JButton exit;

    private final JFileChooser chooser = new JFileChooser();
    private final TrayIcon tray;

    public Starter() {
        super("Idiolect");
        setIconImage(new ImageIcon(Starter.class.getResource("logo.png")).getImage());

        UIManager.put("TitledBorder.font", UIManager.getFont("TitledBorder.font").deriveFont(10F));
        UIManager.put("TextField.font", UIManager.getFont("TextField.font").deriveFont(22F));
        UIManager.put("TextArea.font", UIManager.getFont("TextArea.font").deriveFont(18F));
//        UIManager.put("Button.font", UIManager.getFont("Button.font").deriveFont(25F));
        IOUtil.FOLDER.mkdirs();

        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setCurrentDirectory(IOUtil.FOLDER);

        JPanel buttonsPanel = new JPanel(new GridLayout(1, 0, 6, 0));
        buttonsPanel.add(openFile = new JButton("Open file..."));
        buttonsPanel.add(browseWebStorage = new JButton("Browse web storage"));
        buttonsPanel.add(createNew = new JButton("Create new"));
        buttonsPanel.add(exit = new JButton("Exit"));
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(buttonsPanel, BorderLayout.NORTH);

        openFile.addActionListener(this);
        browseWebStorage.addActionListener(this);
        createNew.addActionListener(this);
        exit.addActionListener(this);

        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(HIDE_ON_CLOSE);
        tray = new TrayIcon(getIconImage(), "Idiolect");
        tray.addActionListener(this);
        WindowAdapter windowAdapter = new WindowAdapter() {
            public void windowIconified(WindowEvent e) {
                showTray();
            }

            public void windowDeiconified(WindowEvent e) {
                hideTray();
            }

            public void windowClosing(WindowEvent e) {
                showTray();
            }

            public void windowOpened(WindowEvent e) {
                hideTray();
            }
        };
        addWindowStateListener(windowAdapter);
        addWindowListener(windowAdapter);
        addComponentListener(new ComponentAdapter() {
            public void componentShown(ComponentEvent e) {
                hideTray();
            }

            public void componentHidden(ComponentEvent e) {
                showTray();
            }
        });
        setVisible(true);
    }

    private void hideTray() {
        setVisible(true);
        if (SystemTray.isSupported() && SystemTray.getSystemTray().getTrayIcons().length > 0) {
            SystemTray.getSystemTray().remove(tray);
        }
    }

    private void showTray() {
        setVisible(false);
        if (SystemTray.isSupported() && SystemTray.getSystemTray().getTrayIcons().length == 0) {
            try {
                SystemTray.getSystemTray().add(tray);
            } catch (AWTException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == openFile) {

            if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) {
                File f = chooser.getSelectedFile();
                Future<Topic> future = Topic.load(f);
                try {
                    Topic topic = future.get(15, TimeUnit.SECONDS);
                    if (topic != null)
                        new TopicEditorDialog(this, topic).setVisible(true);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                } catch (ExecutionException e1) {
                    e1.printStackTrace();
                } catch (TimeoutException e1) {
                    e1.printStackTrace();
                }
            }
            return;
        }
        if (e.getSource() == browseWebStorage) {
            new WebStorageDialog(this);
            return;
        }
        if (e.getSource() == createNew) {
            String name = JOptionPane.showInputDialog(this, "Enter new topic name:");
            if (name != null)
                name = name.trim();
            if (name != null && name.length() > 0)
                new TopicEditorDialog(this, new Topic(name)).setVisible(true);
            return;
        }
        if (e.getSource() == exit) {
            System.exit(0);
        }
        if (e.getSource() == tray) {
            setVisible(true);
            setState(NORMAL);
            return;
        }
    }

    public static void main(String[] args) {
        new Starter().setVisible(true);
    }
}
